var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort("COM4", {
  baudrate: 9600
},false);
// serialPort.on("open", function () {
//   console.log('open');
//   serialPort.on('data', function(data) {
//     console.log('data received: ' + data);
//   });
// });
var revDataFlag = 0;
// var g_revData = [];
var g_revData = new Array(255);

serialPort.open(function (error) {
  if ( error ) {
    console.log('failed to open: '+error);
  } else {
    console.log('open serialport ok');
    serialPort.on('data', function(data) {
      console.log('data received: ' + data);
      if( revDataFlag == 0 )
      {
        g_revData.splice(0,255);
        for (var i=0; i < data.length; i++) {
          g_revData.push( data[i] );
        }
        revDataFlag = 1;
        setTimeout(function()
        {
          timeOver = 10;
          revDataFlag = 0;
          mb_pdu_treate(g_revData);
          // console.log(g_revData);
        },500);
      }
      else
      {
        for (var i=0; i < data.length; i++) {
          g_revData.push( data[i] );
        }
      }
    });
  }
});

function mb_pdu_treate(data){
  this.data=data;
  console.log(this.data);
  var test = group_data_select(0);
  console.log(test);
  //console.log(global.group_data);
}

function group_data_select(index)
{
  var temp  = new Array();
  for (var i=0; i < global.group_data.length; i++) 
  {
    if(global.group_data[i].group == index)
    {
      temp.push(global.group_data[i]);
    }
  }
  return temp;
}
// var mbRd_04_0010 = [0x01,0x04,0x00,0x10,0x00,0x0b,0xff,0xff];
// var mbRd_04_0020 = [0x01,0x04,0x00,0x20,0x00,0x08,0xff,0xff];
// var mbRd_04_0030 = [0x01,0x04,0x00,0x30,0x00,0x05,0xff,0xff];
// var mbRd_04_0040 = [0x01,0x04,0x00,0x40,0x00,0x06,0xff,0xff];

var mbRd_02_0000 = [0x01,0x02,0x00,0x00,0x00,0x28,0xff,0xff];
var mbRd_02_0040 = [0x01,0x02,0x00,0x40,0x00,0x44,0xff,0xff];
var mbRd_02_01C0 = [0x01,0x02,0x01,0xC0,0x00,0x13,0xff,0xff];
var mbRd_02_01E0 = [0x01,0x02,0x00,0xE0,0x00,0x13,0xff,0xff];
var mbRd_03_0000 = [0x01,0x03,0x00,0x00,0x00,0x12,0xff,0xff];
var mbRd_04_0010 = [0x01,0x04,0x00,0x10,0x00,0x46,0xff,0xff];

var mbRdData = [mbRd_02_0000,mbRd_02_0040,mbRd_02_01C0,mbRd_02_01E0,mbRd_03_0000,mbRd_04_0010];
var timeOver = 0;
var index = 6;

setInterval(function () {
    if(++timeOver > 10) timeOver = 10;
    if(timeOver >= 10)
    {
      timeOver = 0;
      if(++index >=6 ) index = 0;
        serialPort.write(mbRdData[index], function(err, results) {});
    }
  }, 300);

//--------------------------------------------
// serialPort.list(function (err, ports) {
//   ports.forEach(function(port) {
//     console.log(port.comName);
//     console.log("------------------------------");
//      console.log(port.pnpId);
//      console.log(port.manufacturer);
//      console.log("------------------------------");
//   });
// });
//--------------------------------------------
module.exports = serialPort;
